#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

void writer(int wfd)
{
    const char* str = "hello yss";
    char buffer[128];//长的字符串
    int cnt = 0;//计数
    pid_t pid = getpid();
    while(1)
    {
        //将str字符串，cnt计数,pid合成一个大的字符串打包为buffer，使用上更安全
        snprintf(buffer, sizeof(buffer), "message: %s, pid: %d, count: %d", str, pid, cnt);
        write(wfd, buffer, strlen(buffer)+1);//将buffer写入文件
        cnt++;
        sleep(1);
    }
}

void reader(int rfd)
{
    char buffer[1024];
    while(1)
    {
        //read别写漏了，没读出来打印个寂寞
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);//从文件里面用buffer读出来，如何打印
        (void)n;
        printf("father get message: %s\n", buffer);
        sleep(1);
    }
}

int main()
{
    //创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    if(n<0) return 1;
    printf("pipefd[0]: %d, pipefd[1]: %d\n", pipefd[0], pipefd[1]);//3  4

    //进程间通信——创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        //子进程写
        close(pipefd[0]);//关闭读
        writer(pipefd[1]);//实现写
        exit(0);
    }
    //父进程读
    close(pipefd[1]);//关闭写
    reader(pipefd[0]);//实现读
    wait(NULL);//防止僵尸
    return 0;
}